﻿using Account.Output;
using Account;
using Bridge.Shared.Models;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Users;
using Users.Input;
using Users.Output;
using Volo.Abp.AspNetCore.Mvc;
using Menus.Input;
using Menus.Output;
using Menus;
using Microsoft.AspNetCore.Http;
using Volo.Abp.DependencyInjection;
using Rong.EasyExcel;
using Rong.EasyExcel.Models;
using Volo.Abp;

namespace Bridge.System.HttpApi
{
    [Route("[controller]/[action]")]
    public class UserController:AbpController
    {
        private readonly IUserService _userService;
        private readonly IAbpLazyServiceProvider _provider;
        public UserController(IUserService userService, IAbpLazyServiceProvider provider) {
            this._userService = userService;
            this._provider = provider;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResponseResult<UserInfoOutput>> GetPageListAsync([FromBody] GetUserPageListInput input)
        {
            try
            {
                return await _userService.GetPageListAsync(input);
            }
            catch (Exception ex)
            {
                return PageResponseResult<UserInfoOutput>.Fail(ex.Message);
            }
        }

        [HttpPost]
        public async Task<ResponseResult<CreateUserOutput>> CreateUser([FromBody]CreateUserInput input)
        {
            try
            {
                
                return await _userService.CreateUser(input);
            }
            catch (Exception ex)
            {
                return ResponseResult<CreateUserOutput>.Fail(ex.Message);
            }
        }
        [HttpPost]
        public async Task<ResponseResult> DeleteAsync([FromBody]  IdsInput<Guid> input)
        {
            try
            {
                return await _userService.DeleteAsync(input);
            }
            catch (Exception ex)
            {
                return ResponseResult.Fail(ex.Message);
            }
        }
        [HttpPost]

        public async Task<ResponseResult> UpdateAsync([FromBody] UpdateUserInput input)
        {
            try
            {
                return await _userService.UpdateAsync(input);
            }
            catch (Exception ex)
            {
                return ResponseResult.Fail(ex.Message);
            }
        }
        [HttpPost]
        public async Task<ResponseResult> UpdateProfile([FromBody] UserProfileinput input)
        {
            try
            {
                return await _userService.UpdateProfile(input);
            }
            catch (Exception ex)
            {
                return ResponseResult.Fail(ex.Message);
            }
        }
        [HttpGet]
        public async Task<ResponseResult<UserProfileOutput>> Profile()
        {
            try
            {
                return await _userService.Profile();
            }
            catch (Exception ex)
            {
                return ResponseResult<UserProfileOutput>.Fail(ex.Message);
            }
        }

        [HttpGet]
        public async Task<ResponseResult<UserInfoOutput>> GetInfo()
        {
            try
            {
                return await _userService.GetInfo();
            }
            catch (Exception ex)
            {
                return ResponseResult<UserInfoOutput>.Fail(ex.Message);
            }
        }
        [HttpGet]
        public async Task<ResponseResult<List<KeyValueOutput>>> InitRoles()
        {
            try
            {
                return await _userService.InitRoles();
            }
            catch (Exception ex)
            {
                return ResponseResult<List<KeyValueOutput>>.Fail(ex.Message);
            }
        }
        [HttpGet("{id}")]
        public async Task<ResponseResult<UserInfoOutput>> GetUserById(Guid id)
        {
            try
            {
                return await _userService.GetUserById(id);
            }
            catch (Exception ex)
            {
                return ResponseResult<UserInfoOutput>.Fail(ex.Message);
            }
        }
        [HttpPost]
        public async Task<ResponseResult> ChangeIsActive([FromBody]ChangeUseStatusInput input)
        {
            try
            {
                return await _userService.ChangeIsActive(input);
            }
            catch (Exception ex)
            {
                return ResponseResult.Fail(ex.Message);
            }
        }

        [HttpPost]
        public async Task<ResponseResult<ImportUserOutput>> ImportUser([FromForm] IFormCollection formCollection)
        {
            try
            {
                var file = formCollection.Files.FirstOrDefault();
                if (file == null)
                {
                    throw new ArgumentException("上传文件为空");
                }
                long size = file.Length;
                if (size <= 0)
                {
                    throw new ArgumentException("传递文件为空");
                }
                else if (size / 1024 >= 10 * 1024)
                {
                    throw new ArgumentException("大小不能超过10M");
                }

                if (!file.FileName.Contains(".xlsx") && !file.FileName.Contains(".xls"))
                {
                    throw new ArgumentException("Excel格式错误，只能是xlsx,xls");
                }
                var _excelImportManager = _provider.LazyGetRequiredService<IExcelImportManager>();

                var data = await _excelImportManager.ImportAsync<ImportUserInput>((await file.GetAllBytesAsync()), opt =>
                {
                    opt.SheetIndex = 0;
                    opt.HeaderRowIndex = 2;
                    opt.DataRowStartIndex = 3;
                    opt.ValidateMode = ExcelValidateModeEnum.ReadBook;//可设置异常处理模式
                });
                //获取有效数据
                var validData = data.GetValidData().ToList();
                //获取错误信息，若无错误则返回null
                var error = data.GetErrorMessage();
                //无效数据列表
                var invalid = data.GetInvalidData().ToList();

                var result = new ImportUserOutput();
                if (invalid.Any())
                {
                    result.FailCount += invalid.Count();
                    result.ErrorMsg = error;
                }
                else
                {
                    result = await _userService.ImportUserAsync(validData);
                }
                return ResponseResult<ImportUserOutput>.Success("ok", result);
            }
            catch (BusinessException e)
            {
                return ResponseResult<ImportUserOutput>.Fail("失败：" + e.Code);
            }
            catch (Exception e)
            {
                return ResponseResult<ImportUserOutput>.Fail("失败：" + e.Message);
            }
        }
    }
}
